﻿using DataAccess.DAL;
using DataAccess.DTO;
using DataAccess.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class RobotController : BaseController
    {
        public ActionResult Index()
        {

            return View();
        }

        [HttpPost]
        public JsonResult GetRobots()
        {
            RobotDAL RobotDAL = new RobotDAL();

            string keyword = XYD.Common.Request.GetFormString("keyword");
            int limit = XYD.Common.Request.GetFormInt("limit", 10);
            int offset = XYD.Common.Request.GetFormInt("offset", 1);
            int state = XYD.Common.Request.GetFormInt("state", -1);
            string sortName = XYD.Common.Request.GetFormString("sortName");
            string sortOrder = XYD.Common.Request.GetFormString("sortOrder");

            string strWhere = " 1=1  ";
            strWhere += string.Format(" and promoter_id='{0}' ", UserSession.user_id);

            string orderbys = (string.IsNullOrEmpty(sortName) ? " state desc " : sortName + " " + sortOrder);

            if (state != -1)
            {
                strWhere += " and state=" + state;
            }

            if (!string.IsNullOrEmpty(keyword))
            {
                strWhere += string.Format(" and (name like '%{0}%'  activation like '%{0}%' ) ", keyword);
            }

            int count = 0;

            List<Robot> users = RobotDAL.GetRobots(strWhere, orderbys, limit, (offset / limit) + 1, out count);

            Result result = new Result();
            result.State = true;
            result.Message = "查询成功";
            result.Datas = new PageData<Robot> { Total = count, Rows = users, PageIndex = (offset / limit) + 1, PageSize = limit };

            return Json(result);
        }

        [HttpGet]
        public ActionResult Edit(string activation = "")
        {
            RobotDAL RobotDAL = new RobotDAL();

            Robot Robot;
            if (activation != "")
            {
                Robot = RobotDAL.Get(activation);
            }
            else
            {
                Robot = new Robot();
                Robot.activation = "";
                Robot.state = 1;
            }

            List<AgencyUsers> users = new List<AgencyUsers>();
            users = new AgencyUsersDAL().GetUsers(UserSession.user_id);
            ViewBag.Users = users;

            return View(Robot);
        }

        [HttpPost]
        public JsonResult Edit()
        {
            dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(XYD.Common.Utils.UrlDecode(Request.Form.ToString()));

            RobotDAL RobotDAL = new RobotDAL();

            Robot robot = new Robot();

            if (obj.activation != null && obj.activation.Value != "")
            {
                if (RobotDAL.Exist(obj.account.Value, obj.activation.Value))
                {
                    return Json(new Result { State = false, Message = "已存在相同机器人账号" });
                }

                robot = RobotDAL.Get(obj.activation.Value);

                robot.name = obj.name.Value;
                robot.account = obj.account.Value;
                robot.password = obj.password.Value;
                robot.state = int.Parse(obj.state.Value);

                bool boo = RobotDAL.Update(robot);

                return Json(new Result { State = boo, Message = boo ? "更新成功" : "更新失败" });
            }
            else
            {
                if (RobotDAL.Exist(obj.account.Value, ""))
                {
                    return Json(new Result { State = false, Message = "已存在相同机器人账号" });
                }

                robot.name = obj.name.Value;
                robot.account = obj.account.Value;
                robot.password = obj.password.Value;
                robot.state = int.Parse(obj.state.Value);
                robot.last_date = DateTime.Now;
                robot.add_date = DateTime.Now;
                robot.is_delete = 0;

                bool boo = RobotDAL.Insert(robot);

                return Json(new Result { State = boo, Message = boo ? "添加成功" : "添加失败" });
            }
        }

        public JsonResult Generate()
        {
            int length = 20;

            //if (length < 1 || length>20)
            //{
            //    return Json(new Result { State = false, Message = "生成个数应该大于0且小于20" }, JsonRequestBehavior.AllowGet);
            //}

            RobotDAL robotDAL = new RobotDAL();

            for (int i = 0; i < length; i++)
            {
                Robot robot = new Robot();

                robot.activation = Guid.NewGuid().ToString("N");

                robot.name = "";
                robot.account = "";
                robot.password = "";
                robot.last_date = DateTime.Now;
                robot.add_date = DateTime.Now;
                robot.state = 0;
                robot.is_delete = 0;

                robotDAL.Insert(robot);
            }

            return Json(new Result { State = true, Message = "生成成功" }, JsonRequestBehavior.AllowGet);
        }




        [HttpPost]
        public JsonResult regRobot(DataAccess.ViewModel.Web.RobotReg vm)
        {
            var res = new Result() { State = false, Message = "注册失败" };

            if (vm != null)
            {
                if (string.IsNullOrEmpty(vm.rname) || string.IsNullOrEmpty(vm.rid) || string.IsNullOrEmpty(vm.rpw1))
                {
                    res.Message = "参数错误";
                }
                else
                {
                    var rids = vm.rid.Split(',');
                    if (rids.Length > 0)
                    {
                        RobotDAL dal = new RobotDAL();
                        var succeedStr = "";
                        var errStr = "";
                        int succendCount = 0;
                        int errCount = 0;
                        for (int i = 0; i < rids.Length; i++)
                        {
                            if (rids.Length > 1)
                            {
                                vm.rname += vm.snum++;
                            }

                            Robot model = new Robot() { activation = vm.rid, account = vm.rname, password = vm.rpw1 };
                            var dalRes = dal.RegRobotAccent(model);

                            if (dalRes ==1 )
                            {
                                succendCount++;

                                succeedStr += vm.rname + " 注册成功！\r\n";
                            }
                            else if (dalRes == -1)
                            {
                                errCount++;
                                errStr += vm.rname + " 改用户名已经存在！注册失败\r\n";
                            }
                            else
                            {
                                errCount++;
                                errStr += vm.rname + " 注册失败\r\n";
                            }
                             
                        }
                        res.State =succendCount>0;
                        res.Message =string.Format("成功{0}个，失败{1}个\r\n {2}{3}",succendCount,errCount,succeedStr,errStr);
                    }
                    else
                    {
                        res.Message = "参数错误";
                    }
                }
            }
            return Json(res, JsonRequestBehavior.AllowGet);
        }

    }
}

